package com.round.card

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.graphics.Camera
import android.view.animation.Animation
import android.view.animation.DecelerateInterpolator
import android.view.animation.Transformation

/**
 * Author: Wu Chang
 *
 * Date: 2023/9/19 11:05
 */
class TurnAnimation(private val startR: Float,
                    private val animValue: (Int) -> Unit, private val animDuration:Long = 1000L) : Animation() {
    private var centerX: Int = 0
    private var centerY: Int = 0
    private var camera: Camera = Camera()

    private val animator: ValueAnimator = ValueAnimator.ofInt(0, 180)

    init {
        animator.addUpdateListener { animation: ValueAnimator ->
            animValue.invoke(animation.animatedValue as Int)
        }
    }

    override fun initialize(
        width: Int, height: Int, parentWidth: Int,
        parentHeight: Int
    ) {
        super.initialize(width, height, parentWidth, parentHeight)
        //获取中心点坐标
        centerX = width / 2
        centerY = height / 2
//        //动画执行时间  自行定义
//        duration = animDuration
        animator.setDuration(animDuration)
        animator.interpolator = DecelerateInterpolator()
        interpolator = DecelerateInterpolator()
        animator.start()
    }

    override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
        val matrix = t.matrix
        camera.save()
        //中心是绕Y轴旋转  这里可以自行设置X轴 Y轴 Z轴
        // 180旋转到背面， 360旋转到一周
        camera.rotateY(180 * interpolatedTime + startR)
        //把我们的摄像头加在变换矩阵上
        camera.getMatrix(matrix)
        camera.setLocation(0f, 0f, 300f)
        //设置翻转中心点
        matrix.preTranslate(-centerX.toFloat(), -centerY.toFloat())
        matrix.postTranslate(centerX.toFloat(), centerY.toFloat())
        camera.restore()
    }

    @SuppressLint("Recycle")
    override fun start() {
        super.start()
    }
}
